//
//  MyViewController.m
//  BeautyClother
//
//  Created by dllo on 15/8/21.
//  Copyright (c) 2015年 宋爽. All rights reserved.
//

#import "MyViewController.h"
#import "MyZoneCell.h"
#import "CollectionViewController.h"
#import "ImageViewController.h"
#import "UIImageView+WebCache.h"
#import "DKNightVersion.h"
#import "PhotoViewController.h"
#import "define.h"
#import "DarkCell.h"
#import "AppDelegate.h"
@interface MyViewController ()<UITableViewDataSource, UITableViewDelegate,ImageDelegate, UIScrollViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UIAlertViewDelegate>

@property (nonatomic, retain) UITableView *table;
@property (nonatomic, retain) UIImageView *ima;

@property (nonatomic, assign) CGFloat offWidth;
@property (nonatomic, assign) CGFloat offHeight;
@property (nonatomic, retain) UIImagePickerController *picker;
@property (nonatomic, retain) UIButton *button;
@property (nonatomic, assign) CGFloat con;
@property (nonatomic, retain) UIView *dark;

@property (nonatomic, retain) MyZoneCell *cell;
@property (nonatomic, retain) UILabel *label;

@property (nonatomic, retain) NSUserDefaults *userInfo;
@property (nonatomic, retain) NSData *imageData;
@property (nonatomic, retain) NSMutableDictionary *personDic;



@property (nonatomic, retain) NSUserDefaults *bUserInfo;
@property (nonatomic, retain) NSData *bImageData;
@property (nonatomic, retain) NSMutableDictionary *bDic;

@end

@implementation MyViewController

- (void)dealloc
{
    [_ima release];
    [_picker release];
    [_cell release];
    [_table release];
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.offWidth = [[UIScreen mainScreen]bounds].size.width / 375;
        self.offHeight = [[UIScreen mainScreen]bounds].size.height / 667;
        self.userInfo = [NSUserDefaults standardUserDefaults];
        self.personDic = [NSMutableDictionary dictionary];
        self.bUserInfo = [NSUserDefaults standardUserDefaults];
        self.bDic = [NSMutableDictionary dictionary];
        
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self createTableView];
    UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 50)];
    title.font = [UIFont boldSystemFontOfSize:20];
    title.textColor = [UIColor colorWithRed:255/255 green:0 blue:255/255 alpha:0.8];
    title.textAlignment = NSTextAlignmentCenter;
    title.text = @"我的空间";
    self.navigationItem.titleView = title;
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.dark = [[UIView alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
    self.dark.backgroundColor = [UIColor blackColor];
    _dark.alpha = 0.6;
    _dark.userInteractionEnabled = NO;
    
#if 0
    // 使navBar透明
    UINavigationBar *bar = self.navigationController.navigationBar;
    
    [bar setBackgroundImage:[UIImage imageNamed:@"shuiyuan.jpg"] forBarMetrics:UIBarMetricsCompact];
    
    // 去掉黑线
    if ([self.navigationController.navigationBar respondsToSelector:@selector( setBackgroundImage:forBarMetrics:)]){
        NSArray *list=self.navigationController.navigationBar.subviews;
        for (id obj in list) {
            if ([obj isKindOfClass:[UIImageView class]]) {
                UIImageView *imageView=(UIImageView *)obj;
                NSArray *list2=imageView.subviews;
                for (id obj2 in list2) {
                    if ([obj2 isKindOfClass:[UIImageView class]]) {
                        UIImageView *imageView2=(UIImageView *)obj2;
                        imageView2.hidden=YES;
                    }
                }
            }
        }
    }
    
#endif
    
    // Do any additional setup after loading the view.
}

- (void)createTableView
{
    self.table = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 44) style:UITableViewStylePlain];
    [self.view addSubview:self.table];
    self.table.delegate = self;
    self.table.dataSource = self;
    self.table.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.table release];
    
    
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 5;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 0;
    }else
    {
        return 1;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return (300 - 69) * _offHeight  + 69;
    }else
    {
        return 5 * _offHeight;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    static NSString *cellSection = @"section";
    UITableViewHeaderFooterView *my = [tableView dequeueReusableCellWithIdentifier:cellSection];
    if (!my) {
        if (section == 0) {
            my = [[[UITableViewHeaderFooterView alloc]initWithReuseIdentifier:cellSection]autorelease];
            self.ima = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.table.frame.size.width, (300 - 69) * _offHeight  + 69)];
            [my addSubview:_ima];
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(selectImage:)];
            [_ima addGestureRecognizer:tap];
            _ima.alpha = 0.6;
            _ima.userInteractionEnabled = YES;
            [tap release];
            //_ima.image = [UIImage imageNamed:@"10.png"];
            
            
            
            self.button = [[UIButton alloc]initWithFrame:CGRectMake(150 *_offWidth, (120 - 69) * _offHeight  + 69, 80  * _offWidth, 80 * _offHeight)];
            [my addSubview:_button];
            
            _button.layer.cornerRadius = 80  * _offWidth / 2;
            _button.layer.masksToBounds = YES;
            [_button setImage:[UIImage imageNamed:@"my.png"] forState:UIControlStateNormal];
            _button.backgroundColor = [UIColor clearColor];
            [_button addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
            _button.layer.borderColor = [[UIColor whiteColor]CGColor];
            _button.layer.borderWidth = 5;
            [_button release];
            
            self.label = [[UILabel alloc]initWithFrame:CGRectMake(120 *_offWidth, (210 - 69) * _offHeight + 69, 135 *_offWidth, 30 * _offHeight)];
            _label.backgroundColor = [ UIColor clearColor];
            [my addSubview:_label];
            self.label.text = @"啦啦啦啦啦啦";
            
            
            _label.textAlignment = 1;
            [_label release];
            
        }
    }
    return my;
}

- (void)click:(UIButton *)button
{
    self.picker = [[UIImagePickerController alloc] init];
    _picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    _picker.allowsEditing = YES;
    _picker.delegate = self;
    [self presentViewController:_picker animated:YES completion:^{
        
    }];
    [_picker release];
    
}

- (void)passImage:(NSString *)picUrl
{
    
    [self.ima sd_setImageWithURL:[NSURL URLWithString:picUrl] placeholderImage:[UIImage imageNamed:@"zw.jpg"] options:SDWebImageCacheMemoryOnly progress:^(NSInteger receivedSize, NSInteger expectedSize) {
        
    } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        self.bUserInfo = [NSUserDefaults standardUserDefaults];
        self.bImageData = UIImagePNGRepresentation(self.ima.image);
        
        [self.bDic setObject:_bImageData forKey:@"bImage"];
        
        [self.bUserInfo setObject:self.bDic forKey:@"bPerson"];
        [self.bUserInfo setObject:self.bDic forKey:B_IMAGE];
        [self.bUserInfo synchronize];
    }];
    
    
}



- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    
    [_button setImage:[info objectForKey:@"UIImagePickerControllerEditedImage"] forState:UIControlStateNormal];
    [_picker dismissViewControllerAnimated:YES completion:^{
        
    }];
    // 将用户信息存到本地(NSUserDefaults 数据持久化)
    [self.button setImage:[info objectForKey:UIImagePickerControllerEditedImage]forState:UIControlStateNormal];
    self.userInfo = [NSUserDefaults standardUserDefaults];
    self.imageData = UIImagePNGRepresentation([info objectForKey:UIImagePickerControllerEditedImage]);
    
    
    [self.personDic setObject:_imageData forKey:@"image"];
    [self.userInfo setObject:self.personDic forKey:@"person"];
    //存储到本地
    [self.userInfo setObject:self.personDic forKey:MY_IMAGE];
    //将数据同步到本地
    [self.userInfo synchronize];
    
    
    
}

- (void)selectImage:(UITapGestureRecognizer *)tap
{
    ImageViewController *image = [[ImageViewController alloc]init];
    image.hidesBottomBarWhenPushed = YES;
    image.delegate = self;
    [self.navigationController pushViewController:image animated:YES];
    [image release];
}

- (void)viewDidAppear:(BOOL)animated
{
    
    NSDictionary *dic = [[NSUserDefaults standardUserDefaults] objectForKey:@"person"];
    NSData *imageData = [dic objectForKey:@"image"];
    [self.button setImage:[UIImage imageWithData:imageData] forState:UIControlStateNormal];
    
    
    NSDictionary *bDic = [[NSUserDefaults standardUserDefaults] objectForKey:@"bPerson"];
    NSData *bimageData = [bDic objectForKey:@"bImage"];
    if (!bimageData) {
        return;
    }
    self.ima.image = [UIImage imageWithData:bimageData];
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSArray *arr = @[@"我的收藏",  @"清除缓存",  @"关于我们", @"夜间模式"];
    NSArray *image = @[@"sun.png", @"qingchu.png" ,@"snow.png",@"yl.png"];
    
    if (indexPath.section == 4) {
        DarkCell *cell = [tableView dequeueReusableCellWithIdentifier:@"dark"];
        if (!cell) {
            cell = [[DarkCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"dark"];
        }
        cell.name.text = [arr objectAtIndex:indexPath.section - 1];
        cell.image.image = [UIImage imageNamed:[image objectAtIndex:indexPath.section - 1]];
        [cell.swith addTarget:self action:@selector(switchAction:) forControlEvents:UIControlEventValueChanged];
        
        NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
        NSString *filePath = [NSString stringWithFormat:@"%@/drack", path];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        //判断本地是否有这个文件
        if ([fileManager fileExistsAtPath:filePath]) {
            //将文件里的东西取出来(解档)
            NSString *str = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
            if ([str isEqualToString:@"no"]) {
                cell.swith.on = NO;
            } else
            {
                cell.swith.on = YES;
            }
        } else
        {
            //归档
            NSString *str = @"no";
            [NSKeyedArchiver archiveRootObject:str toFile:filePath];
        }

        
        
        return cell;
    } else{
    
    
    self.cell = [tableView dequeueReusableCellWithIdentifier:@"zone"];
    self.cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    if (_cell == nil) {
        _cell = [[MyZoneCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"zone"];
        _cell.name.text = [arr objectAtIndex:indexPath.section - 1];
        _cell.image.image = [UIImage imageNamed:[image objectAtIndex:indexPath.section - 1]];
        if (indexPath.section == 2) {
            
            
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(swip:)];
            [_cell.contentView addGestureRecognizer:tap];
            [tap release];
        }
    }
        
        
    }
    _cell.backgroundColor = [UIColor clearColor];
    return _cell;
    
    
}

- (void)switchAction:(UISwitch *)swit
{
    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
    NSString *filePath = [NSString stringWithFormat:@"%@/drack", path];
    AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    if (swit.on == YES) {
        [app.window addSubview:_dark];
        [NSKeyedArchiver archiveRootObject:@"yes" toFile:filePath];
        
        
    }else{
        [app.dark removeFromSuperview];
        [_dark removeFromSuperview];
        [NSKeyedArchiver archiveRootObject:@"no" toFile:filePath];
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 3) {
        return 10 * _offHeight;
    }else
    {
        
        return 5  *_offHeight;
    }
}

#pragma mark -- 清除缓存
- (long long) fileSizeAtPath:(NSString*) filePath{
    NSFileManager* manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]){
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}


//遍历文件夹获得文件夹大小，返回多少M
- (float ) folderSizeAtPath:(NSString*) folderPath{
    NSFileManager* manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:folderPath])
        return 0;
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    NSString* fileName;
    long long folderSize = 0;
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
    }
    return folderSize/(1024.0*1024.0);
}

- (void)swip:(UITapGestureRecognizer *)tap
{
    
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"是否清除缓存" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
    [alert show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        dispatch_async(
                       dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
                       , ^{
                           
                           NSLog(@"清除缓存");
                           NSString *cachPath = [[NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0]stringByAppendingString:@"/Caches/"];
                           
                           NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachPath];
                           NSLog(@"%@", files);
                           for (NSString *p in files) {
                               NSError *error;
                               NSString *path = [cachPath stringByAppendingPathComponent:p];
                               if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
                                   [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
                               }
                           }
                           
                       });
        
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            CollectionViewController *coll = [[CollectionViewController alloc]init];
            coll.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:coll animated:YES];
            [coll release];
            
        }
    }
    
    if (indexPath.section == 3) {
        PhotoViewController *photo = [[PhotoViewController alloc]init];
        [self.navigationController pushViewController:photo animated:YES];
        [photo release];
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView == self.table) {
        if (self.table.contentOffset.y < 80) {
            scrollView.zoomScale = scrollView.contentOffset.y * 0.02;
        }
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
